#include "Socket.h"
#include "Tracer.h"
#include "FileUtil.h"
#include "StrUtil.h"
#include "DateTime.h"
#include "ArgUtil.h"
#include <unistd.h>
#include <iostream>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <signal.h>

using namespace libemb;

int main(int argc, char* argv[])
{
	std::string argValue;
	ArgOption  argOption;
	int interval=1000000;
	uint16 port=5555;
	std::string ip = "127.0.0.1";
	std::string localip = "127.0.0.1";
	Tracer::getInstance().setLevel(TRACE_LEVEL_DBG);
	
	argOption.addOption("h", 0);	/* -h:帮助 */
	argOption.addOption("p", 1);	/* -p:指定端口 */
	argOption.addOption("i", 1);	/* -i:指定IP */
	argOption.addOption("l", 1);	/* -l:本地IP */
	argOption.addOption("t", 1);	/* -t:发送间隔 */
	argOption.parseArgs(argc,argv);	/* 解析参数 */

	if(argOption.getValue("h", argValue))
	{
		FilePath filePath(argv[0]);
		TRACE_YELLOW("udp client help:\n");
		TRACE_YELLOW("%s [-h] [-l localip] [-p port] [-i ip] [-t interval]\n",CSTR(filePath.baseName()));
		TRACE_YELLOW("        -h  help\n");
		TRACE_YELLOW("        -l  local ip\n");
		TRACE_YELLOW("        -p  server port\n");
		TRACE_YELLOW("        -i  server ip\n");
		TRACE_YELLOW("        -t  send interval(us)\n");
		return RC_OK;
	}

	if(argOption.getValue("l", argValue))
	{
		localip = argValue;
	}

	if(argOption.getValue("i", argValue))
	{
		ip = argValue;
	}
	
	if(argOption.getValue("p", argValue))
	{
		port = (uint16)StrUtil::stringToInt(argValue);
	}
	else
	{
		TRACE_ERR("tcp client need server port: [-p port]!\n");
		return RC_ERROR;
	}

	if(argOption.getValue("t", argValue))
	{
		interval = StrUtil::stringToInt(argValue);
	}
     /* 客户端建立连接 */
	UdpSocket client;
	if(!client.open(localip,port-1))
	{
		TRACE_ERR("cannot open local socket!\n");
		return RC_ERROR;
	}
	if (!client.setConnection(ip,port))
	{
		TRACE_ERR("cannot connect server: %s:%d\n",CSTR(ip),port);
		return RC_ERROR;
	}
	TRACE_INFO("start send to server: %s:%d interval:%d\n",CSTR(ip),port,interval);
	while(1)
	{
		std::string msg="hello";
		Time startTime = Time::currentTimeMonotonic();
		if(client.sendData(CSTR(msg),msg.size() ,1000)<=0)
		{
			TRACE_ERR("send msg to server error!\n");
		}
		else
		{
			TRACE_INFO("send msg to server ok!\n");
		}
		char buf[64];
		if (client.recvData(buf, sizeof(buf),-1)>0)
		{
			Time duration = Time::currentTimeMonotonic()-startTime;
			TRACE_INFO("get server ack time: %lld us!\n",duration.toMicroSeconds());
		}
		Thread::usleep(interval);
	}
    return 0;
}
